#include "UDP_send.hpp"

#define MAX_PACKET_SIZE 65507

bool sendProcessedImageViaUDP(const Mat &processedImage, int sockfd, const struct sockaddr_in &dest_addr, const vector<int> &encode_params)
{
    vector<uchar> processedImgBuf;
    // JPEG压缩编码处理过的图像
    if (!imencode(".jpg", processedImage, processedImgBuf, encode_params))
    {
        cerr << "处理过的图像编码失败" << endl;
        return false;
    }
    // 发送处理过的图像
    size_t processedTotalSize = processedImgBuf.size();
    const char *processedDataPtr = reinterpret_cast<const char *>(processedImgBuf.data());
    // 发送数据包头
    uint32_t processedPktHeader[2] = {
        htonl(0xABCD1234),
        htonl(processedTotalSize)};
    if (sendto(sockfd, processedPktHeader, sizeof(processedPktHeader), 0,
               (struct sockaddr *)&dest_addr, sizeof(dest_addr)) < 0)
    {
        cerr << "发送处理过的图像数据包头失败" << endl;
        return false;
    }
    // 分片发送数据
    size_t processedSent = 0;
    while (processedSent < processedTotalSize)
    {
        size_t processedChunkSize = min(MAX_PACKET_SIZE, static_cast<int>(processedTotalSize - processedSent));
        ssize_t processedBytesSent = sendto(sockfd, processedDataPtr + processedSent, processedChunkSize, 0,
                                            (struct sockaddr *)&dest_addr, sizeof(dest_addr));
        if (processedBytesSent < 0)
        {
            cerr << "发送处理过的图像数据失败" << endl;
            return false;
        }
        processedSent += processedBytesSent;
    }

    return true;
}
